﻿#' 
#' @TODO  # 统计临床信息中人数所占比
#' @title 统计临床信息中人数所占比
#' @param Data *data.frame*，输入数据 
#' @param Features 要统计的临床信息，字符串向量
#' @param od output_dir 结果输出目录
#' @param SaveFile 是否保存文件，默认`TRUE`，输出`ClinicalInfor.txt`文件
#' @export
#' @author *WYK*
#'
ClinicalInforStat <- function(Data = NULL, Features = c("Age", "Gender", "Stage"), od = "./", SaveFile = T, ...) {
    require(tidyverse)
    require(crosstable)
    require(officer)

    res <- Data %>%
        dplyr::select(all_of(Features)) %>%
        gather(key = "pheno_name", value = "pheno") %>% 
        # pivot_longer(cols = any_of(Features),names_to = "pheno_name", values_to = "pheno") %>%
        mutate(pheno = ifelse(pheno == '',NA,pheno)) %>% 
        dplyr::group_by(pheno_name, pheno) %>%
        # filter(pheno != "NA" & pheno != "") %>%
        dplyr::summarise(n = n()) %>%
        dplyr::group_by(pheno_name) %>%
        mutate(n_per = str_c(round(n / sum(n) * 100, 2), "%")) %>%
        mutate(perc = str_c(n, "(", n_per, ")"))

    df <- Data %>% select(Features) 
    df_stat <- map_dfc(colnames(df), function(x) {
        df2 <- df
        df2[, x] <- df[, x] %>%
            as.character() %>%
            replace_na("unknow")
        return(df2[, x, drop = F])
    })
    table_tmp <- crosstable(data = df_stat, cols = colnames(df_stat), total = "row", percent_pattern = "{n} ({p_col})")
    docx_tmp <- officer::read_docx() %>% body_add_crosstable(x = table_tmp, body_fontsize = 10, header_fontsize = 12)
   
    if (SaveFile) {
        if (!dir.exists(od)) {
            fs::dir_create(path = od, recurse = T)
        }

        write_tsv(x = res, file = file.path(od, "SupplementaryTable_ClinicalInfor.txt"))
        print(docx_tmp, target = paste0(od, "SupplementaryTable_ClinicalInfor.docx"))
    }

    print(res %>%
        knitr::kable(align = "c"))

    return(res)
}

# Covariates Type
